//
//  BigMVViewController.m
//  STL_ Animation
//
//  Created by DJtd on 16/4/6.
//  Copyright © 2016年 STL. All rights reserved.
//

#import "BigMVViewController.h"
#import "CoreDataManager.h"
#import "MVCollection.h"
#import "YSingleCollection.h"
/*********************************************************/
@interface BigMVViewController ()<STL_PlayRecognizerDelegate>
//播放基本内容
@property (nonatomic, strong) STLAvPlayer *avPlayer;
@property (nonatomic, strong) AVPlayerItem *playerItem;
@property (nonatomic, strong) UIView *playView;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) NSTimer *timerLock;
@property (nonatomic, strong) NSTimer *timerLocking;
//大屏上方控件
@property (nonatomic, strong) UIView *topView;
@property (nonatomic, strong) UIButton *returnButton;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIButton *lockButton;
@property (nonatomic, strong) UIButton *lockingButton;
@property (nonatomic, strong) UIButton *downLoadButton;
@property (nonatomic, strong) UIButton *collectButton;
//大屏下方控件
@property (nonatomic, strong) UIView *descView;
@property (nonatomic, strong) UIButton *bigButton;
@property (nonatomic, strong) UIButton *startButton;
@property (nonatomic, strong) UISlider *playSlider;
@property (nonatomic, strong) UILabel *timeBeginLabel;
@property (nonatomic, strong) UILabel *timeEndLabel;
@property (nonatomic, strong) UIButton *frontButton;
@property (nonatomic, strong) UIButton *backButton;
@property (nonatomic, strong) UIButton *changeButton;
@property (nonatomic, strong) UIButton *autoButton;
@property (nonatomic, strong) UIImageView *imView;
//
@property (nonatomic, assign) CGPoint startPanPoint;

@property (nonatomic, strong) UISlider *slider;
@property (nonatomic, strong) UISlider *volumeSlider;

@property (nonatomic, strong) CoreDataManager *coreDataManager;
@property (nonatomic, strong) NSMutableArray *mvCollectArr;

@property (nonatomic, assign) BOOL isCollect;
@end



@implementation BigMVViewController

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
/*********************************************************/
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.avPlayer = [STLAvPlayer shareAVPlayer];

    self.isCollect = NO;
    self.coreDataManager = [CoreDataManager shareCoreDataManager];
    NSLog(@"%@", [self.coreDataManager applicationDocumentsDirectory]);
    
    self.mvCollectArr = [NSMutableArray arrayWithCapacity:0];
    [self getData];
    
    
    
//    NSLog(@"悦单要收藏的内容－－－－－－%@, %@, %@, %@, %@", self.ymvModel.videoCount, self.ymvModel.totalViews, self.ymvModel.totalFavorites, self.ymvModel.updateTime, self.ymvModel.integral);
    //
    
    [self playMV];
    [self getTitleText];

    //创建手势
    UIPanGestureRecognizer *reco = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panAction:)];
    [self.view addGestureRecognizer:reco];
    
}


/*********************************************************/
#pragma mark - 创建播放界面
- (void)playMV {

    self.playView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [self.view addSubview:self.playView];
    self.playView.backgroundColor = [UIColor blackColor];

    self.avPlayer.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.avPlayer];
    self.avPlayer.playerLayer.frame = CGRectMake(ScreenWidth / 2 - ScreenHeight / 2, ScreenHeight / 2 - ScreenWidth / 2, ScreenHeight, ScreenWidth);
    //旋转90度
    self.avPlayer.playerLayer.transform = CATransform3DMakeRotation(M_PI_2, 0, 0, 1);
    
    
    
    
    //设置显示图层视频的宽高比自动适应播放窗口的大小
    self.avPlayer.playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
    self.avPlayer.playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
    //
    [self.playView.layer addSublayer:self.avPlayer.playerLayer];
    //设置音量
    self.avPlayer.volume = 1.0f;
    

#pragma mark - 上下view
    //x为宽与心，y为y与高，宽为屏幕宽，高为屏幕高.
    self.topView = [UIView new];
    [self.playView addSubview:self.topView];
    self.topView.backgroundColor = [UIColor blackColor];
    self.topView.alpha = 0.7;
    self.topView.transform = CGAffineTransformMakeRotation(M_PI_2);
    self.topView.frame = CGRectMake(ScreenWidth * 0.82, 0, ScreenWidth * 0.18, ScreenHeight);
    //
    self.descView = [UIView new];
    [self.playView addSubview:self.descView];
    self.descView.backgroundColor = [UIColor blackColor];
    self.descView.alpha = 0.7;
    self.descView.transform = CGAffineTransformMakeRotation(M_PI_2);
    self.descView.frame = CGRectMake(0, 0, ScreenWidth * 0.18, ScreenHeight);
    
#pragma mark - title
    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(40, 10, self.descView.height / 2, 30)];
    [self.topView addSubview:self.titleLabel];
    self.titleLabel.textColor = [UIColor whiteColor];
    self.titleLabel.font = [UIFont systemFontOfSize:15];
    
#pragma mark - 关闭按钮
    self.returnButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.returnButton setImage:[[UIImage imageNamed:@"return"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    [self.topView addSubview:self.returnButton];
    [self.returnButton addTarget:self action:@selector(closeAction) forControlEvents:UIControlEventTouchUpInside];
    self.returnButton.frame = CGRectMake(10, 10, 30, 30);
    
    [self creatVoiceSlider];
    [self creatThreeButton];
    [self creatDescButton];
    [self creatTimeLabel];
    [self creatTypeButton];
    [self creatLockingButton];
    //
    //
    

}


#pragma mark - 声音slider
- (void)creatVoiceSlider {
    MPVolumeView *volumeView = [[MPVolumeView alloc] init];
    [self.playView addSubview:volumeView];

    volumeView.frame = CGRectMake(-1000, -1000, 100, 100);
    
    self.slider = [[UISlider alloc]init];
    self.slider.backgroundColor = [UIColor blueColor];
    for (UIControl *view in volumeView.subviews) {
        if ([view.superclass isSubclassOfClass:[UISlider class]]) {
            
            self.slider = (UISlider *)view;
        }
    }
    self.slider.autoresizesSubviews = NO;
    self.slider.autoresizingMask = UIViewAutoresizingNone;
    [self.view addSubview:self.slider];
    self.slider.hidden = YES;
    
    self.volumeSlider = [[UISlider alloc]initWithFrame:CGRectMake(ScreenWidth * 0.25, ScreenHeight - 40, ScreenWidth * 0.5, 25)];
    self.volumeSlider.minimumValue = 0.0;
    self.volumeSlider.maximumValue = 1.0;
    self.volumeSlider.continuous = YES;
    [self.volumeSlider setThumbImage:[UIImage imageNamed:@"slider"] forState:UIControlStateNormal];
    [self.volumeSlider setMinimumValueImage:[[UIImage imageNamed:@"shengyin"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
    
    self.volumeSlider.minimumTrackTintColor = [UIColor colorWithRed:8/255.0 green:146/255.0 blue:114/255.0 alpha:1];
    [self.volumeSlider addTarget:self action:@selector(volumeChange) forControlEvents:UIControlEventValueChanged];
    [self.playView addSubview:self.volumeSlider];

}
- (void)volumeChange
{
    [[MPMusicPlayerController applicationMusicPlayer] setVolume:self.volumeSlider.value];
}




/*********************************************************/
#pragma mark - 上方button
- (void)creatThreeButton {
    self.downLoadButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.downLoadButton setImage:[[UIImage imageNamed:@"download"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    [self.topView addSubview:self.downLoadButton];
    [self.downLoadButton addTarget:self action:@selector(downLoad) forControlEvents:UIControlEventTouchUpInside];
    self.downLoadButton.frame = CGRectMake(self.topView.height - 40, 10, 30, 30);
    
    //
    self.collectButton = [UIButton buttonWithType:UIButtonTypeSystem];
    
    [self searchFromList];
    
    if (self.isCollect == NO) {
        [self.collectButton setImage:[[UIImage imageNamed:@"collect1"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    } else {
        [self.collectButton setImage:[[UIImage imageNamed:@"collect2"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    }
    
    [self.topView addSubview:self.collectButton];
    [self.collectButton addTarget:self action:@selector(collect) forControlEvents:UIControlEventTouchUpInside];
    self.collectButton.frame = CGRectMake(self.topView.height - 80, 10, 30, 30);
    
    //
    self.lockButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.lockButton setImage:[[UIImage imageNamed:@"lock1"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    [self.topView addSubview:self.lockButton];
    [self.lockButton addTarget:self action:@selector(lock) forControlEvents:UIControlEventTouchUpInside];
    self.lockButton.frame = CGRectMake(self.topView.height - 120, 10, 30, 30);
}




/*********************************************************/
#pragma mark - 下方button
- (void)creatDescButton {
    self.bigButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.bigButton addTarget:self action:@selector(closeAction) forControlEvents:UIControlEventTouchUpInside];
    [self.descView addSubview:self.bigButton];
    [self.bigButton setImage:[[UIImage imageNamed:@"bigandsmall"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    self.bigButton.frame = CGRectMake(self.descView.height - 40, self.descView.width - 40, 30, 30);
    
    
#pragma mark - button
    self.startButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.startButton.frame = CGRectMake(self.descView.width * 0.7 + 10, self.descView.width * 0.2, self.descView.width * 0.7, self.descView.width * 0.7);
    [self.descView addSubview:self.startButton];
    [self.startButton addTarget:self action:@selector(startButtonAction:) forControlEvents:UIControlEventTouchUpInside];

    if (self.avPlayer.isPlayer == YES) {
        [self.startButton setImage:[[UIImage imageNamed:@"pausebig"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    } else {
        [self.startButton setImage:[[UIImage imageNamed:@"playbig"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    }
    
    //清晰度按钮
    self.autoButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.autoButton.frame = CGRectMake(self.descView.height - 80, self.descView.width - 40, 30, 30);
    [self.descView addSubview:self.autoButton];
    [self.autoButton addTarget:self action:@selector(autoDefinition) forControlEvents:UIControlEventTouchUpInside];
    //给播放模式附图片
    if (self.avPlayer.changeType == 0) {   // 标清
        [self.autoButton setImage:[[UIImage imageNamed:@"puqing"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    }
    if (self.avPlayer.changeType == 1) {   // 高清
        [self.autoButton setImage:[[UIImage imageNamed:@"gaoqing"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    }
    if (self.avPlayer.changeType == 2) {   // 超清
        [self.autoButton setImage:[[UIImage imageNamed:@"chaoqing"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    }
    
    
    
    //循环模式按钮
    self.changeButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.changeButton.frame = CGRectMake(self.descView.height - 120, self.descView.width - 40, 30, 30);
    [self.descView addSubview:self.changeButton];
    [self.changeButton addTarget:self action:@selector(typeChange) forControlEvents:UIControlEventTouchUpInside];
    if (self.avPlayer.changeItem == 1) {   // 循环播放
        [self.changeButton setImage:[[UIImage imageNamed:@"danqu"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]  forState:UIControlStateNormal];
    }
    if (self.avPlayer.changeItem == 2) {   // 随机播放
        [self.changeButton setImage:[[UIImage imageNamed:@"suiji"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]  forState:UIControlStateNormal];
    }
    if (self.avPlayer.changeItem == 0) {   // 顺序播放
        [self.changeButton setImage:[[UIImage imageNamed:@"shunxu"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]  forState:UIControlStateNormal];
    }
}

/*********************************************************/
#pragma mark - 锁住按钮
- (void)creatLockingButton {
    self.lockingButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.playView addSubview:self.lockingButton];
    [self.lockingButton setImage:[[UIImage imageNamed:@"lock2"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    self.lockingButton.hidden = YES;
    [self.lockingButton addTarget:self action:@selector(locking) forControlEvents:UIControlEventTouchUpInside];
    self.lockingButton.transform = CGAffineTransformMakeRotation(M_PI_2);
    self.lockingButton.frame = CGRectMake(ScreenWidth / 2 - 20, ScreenHeight - 55, 40, 40);
    
    
}


/*********************************************************/
#pragma mark - timelabel
- (void)creatTimeLabel {
    self.timeBeginLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 40, self.descView.width * 0.2)];
    [self.descView addSubview:self.timeBeginLabel];
    self.timeBeginLabel.font = [UIFont systemFontOfSize:11];
    self.timeBeginLabel.textAlignment = NSTextAlignmentCenter;
    self.timeBeginLabel.textColor = [UIColor whiteColor];
    //
    self.timeEndLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.descView.height - 40, 0, 40, self.descView.width * 0.2)];
    [self.descView addSubview:self.timeEndLabel];
    self.timeEndLabel.textAlignment = NSTextAlignmentCenter;
    self.timeEndLabel.font = [UIFont systemFontOfSize:11];
    self.timeEndLabel.textColor = [UIColor whiteColor];

#warning bughhhh
    self.avPlayer.progressView.frame = CGRectMake(40 + 2, self.descView.width * 0.1 - 1, self.descView.height - 80 - 4, self.descView.width * 0.2 - 4);
    [self.descView addSubview:self.avPlayer.progressView];


    
#pragma mark - timer
    self.timer =  [NSTimer scheduledTimerWithTimeInterval:0.5f  target:self selector:@selector(timeAction) userInfo:nil repeats:YES];
    //slider
    self.playSlider = [[UISlider alloc] initWithFrame:CGRectMake(40, 0, self.descView.height - 80, self.descView.width * 0.2)];
    //设置最大最小值
    self.playSlider.maximumValue = 1.0f;
    self.playSlider.minimumValue = 0.0f;
    
//    self.playSlider.alpha = 0;
    //slider 点击事件
    [self.playSlider addTarget:self action:@selector(sliderAction) forControlEvents:UIControlEventValueChanged];
    [self.playSlider setThumbImage:[UIImage imageNamed:@"slider"] forState:UIControlStateNormal];
    self.playSlider.minimumTrackTintColor = [UIColor colorWithRed:8/255.0 green:146/255.0 blue:114/255.0 alpha:1];
    self.playSlider.maximumTrackTintColor = [UIColor colorWithRed:8/255.0 green:146/255.0 blue:114/255.0 alpha:0];
    [self.descView addSubview:self.playSlider];
    
//    self.avPlayer.progressView.center = self.playSlider.center;
    
    
    
    
#pragma mark - 让控件隐藏
    if (self.topView.hidden == NO) {
        self.timer =  [NSTimer scheduledTimerWithTimeInterval:5.0f  target:self selector:@selector(dispearAction) userInfo:nil repeats:NO];
    }

}







/*********************************************************/
#pragma mark - 创建循环模式按钮
- (void)creatTypeButton {
    
    
    if (self.avPlayer.pageType == 1) {
        //
        self.frontButton = [UIButton buttonWithType:UIButtonTypeSystem];
        self.frontButton.frame = CGRectMake(self.descView.width * 0.1 + 10, self.descView.width * 0.4, self.descView.width * 0.5, self.descView.width * 0.5);
        [self.descView addSubview:self.frontButton];
        [self.frontButton addTarget:self action:@selector(frontMV) forControlEvents:UIControlEventTouchUpInside];
        [self.frontButton setImage:[[UIImage imageNamed:@"back"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
        //
        self.backButton = [UIButton buttonWithType:UIButtonTypeSystem];
        self.backButton.frame = CGRectMake(self.descView.width * 1.5 + 10, self.descView.width * 0.4, self.descView.width * 0.5, self.descView.width * 0.5);
        [self.descView addSubview:self.backButton];
        [self.backButton addTarget:self action:@selector(backMV) forControlEvents:UIControlEventTouchUpInside];
        [self.backButton setImage:[[UIImage imageNamed:@"front"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    }

}




#pragma mark - 关闭视频按钮
- (void)closeAction {
    
    [self.timer invalidate];
    self.timer = nil;
    [self.timerLock invalidate];
    self.timerLock = nil;
    [self.timerLocking invalidate];
    self.timerLocking = nil;

    [[NSNotificationCenter defaultCenter] postNotificationName:@"progress" object:nil];
    
    [self dismissViewControllerAnimated:YES completion:^{
    }];
}


/*********************************************************/
#pragma mark - 控件隐藏
- (void)dispearAction {
    self.topView.hidden = YES;
    self.descView.hidden = YES;
    self.volumeSlider.hidden = YES;
}


#pragma mark - 点击隐藏／显示控件
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    if (self.avPlayer.isLock == NO) {
        if (self.topView.hidden == NO) {
            self.topView.hidden = YES;
            self.descView.hidden = YES;
            self.volumeSlider.hidden = YES;
        } else {
            self.topView.hidden = NO;
            self.descView.hidden = NO;
            self.volumeSlider.hidden = NO;
            [self timeRemove];
        }
    } else {
        self.lockingButton.hidden = NO;
        [self timeLockHidden];
    }
    
    
    // 获取拖动的初始坐标 用于判断上半屏还是下半屏
    UITouch *touch = [touches anyObject];
    
    self.startPanPoint = [touch locationInView:self.view];
}

//创建拖动方法
- (void)panAction:(UIPanGestureRecognizer *)action {
    if (self.avPlayer.isLock == NO) {
        STL_PlayerRecognizer *playerRecognize = [[STL_PlayerRecognizer alloc] init];
        playerRecognize.startPanPoint = self.startPanPoint;
        playerRecognize.panDelegate = self;
        [playerRecognize handleSwipe:action withView:self.view];
        if (action.state == UIGestureRecognizerStateBegan) {
            self.volumeSlider.hidden = NO;
        }
        if (action.state == UIGestureRecognizerStateEnded) {
            self.volumeSlider.hidden = YES;
        }
    }
    
    
}


//拖动后实现
- (void)recognizWithMoveDirection:(STLMoveDirection)direction withChangeValue:(CGFloat)changeValue {
    
    if (self.avPlayer.isLock == NO) {
        
    
        CGFloat light = [UIScreen mainScreen].brightness;
        CGFloat lightChangeSmall = light - changeValue/ScreenWidth/10;
        CGFloat lightChangBig = light + changeValue/ScreenWidth/10;
        
        
        CGFloat voice = self.volumeSlider.value;
        CGFloat voiceChangeSmall = voice - changeValue/ScreenWidth/10;
        CGFloat voiceChangBig = voice + changeValue/ScreenWidth/10;
        
        
        switch (direction) {
            case STLdirectionNone:
                break;
                
            case STLdirectionUp:
            {
                
                [self.timer invalidate];
                self.timer = nil;
                
                self.playSlider.value = self.playSlider.value - changeValue/ScreenHeight/100;
                
                
                [self sliderAction];
                
                self.timer =  [NSTimer scheduledTimerWithTimeInterval:0.5f  target:self selector:@selector(timeAction) userInfo:nil repeats:YES];
            }   break;
                
            case STLdirectionDown:
            {
                [self.timer invalidate];
                self.timer = nil;
                
                self.playSlider.value = self.playSlider.value + changeValue/ScreenHeight/100;
                
                [self sliderAction];
                
                self.timer =  [NSTimer scheduledTimerWithTimeInterval:0.5f  target:self selector:@selector(timeAction) userInfo:nil repeats:YES];
                
            }   break;
                
            case STLdirectionTopLeft:
            {
                if (0 <= light && light <= 1) {
                    if (lightChangeSmall < 0) {
                        lightChangeSmall = 0;
                    }
                    [[UIScreen mainScreen] setBrightness:lightChangeSmall];
                }
                
            }   break;
                
            case STLdirectionTopRight:
            {
                if (0 <= light && light <= 1) {
                    if (lightChangBig > 1) {
                        lightChangBig = 1;
                    }
                    [[UIScreen mainScreen] setBrightness:lightChangBig];
                }
                
            } break;
                
            case STLdirectionBottomLeft:
            {
                if (0 <= voice && voice <= 1) {
                    if (voiceChangeSmall < 0) {
                        voiceChangeSmall = 0;
                    }
                    self.volumeSlider.value = voiceChangeSmall;
                    [[MPMusicPlayerController applicationMusicPlayer] setVolume:self.volumeSlider.value];
                }
            }   break;
                
            case STLdirectionBottomRight:
            {
                if (0 <= voice && voice <= 1) {
                    if (voiceChangBig > 1) {
                        voiceChangBig = 1;
                    }
                    self.volumeSlider.value = voiceChangBig;
                    [[MPMusicPlayerController applicationMusicPlayer] setVolume:self.volumeSlider.value];
                }
            }    break;
                
            default:
                break;
        }
        
    }
}

#pragma mark - 计时隐藏锁
- (void)timeLockHidden {
    self.timerLock = [NSTimer scheduledTimerWithTimeInterval:3.0f target:self selector:@selector(lockishidden) userInfo:nil repeats:NO];
}
#pragma mark - 锁隐藏
- (void)lockishidden {
    self.lockingButton.hidden = YES;
}
#pragma mark - 计时器移除
- (void)timeRemove {
    if (self.avPlayer.isLock == NO) {
        [self.timer invalidate];
        self.timer = nil;
        self.timer =  [NSTimer scheduledTimerWithTimeInterval:5.0f  target:self selector:@selector(dispearAction) userInfo:nil repeats:NO];
    }
}




#pragma mark - 暂停
- (void)startButtonAction:(UIButton *)sender {
    //bool默认为yes
    if (self.avPlayer.isPlayer == YES) {
        [self.avPlayer pause];
        [self.startButton setImage:[[UIImage imageNamed:@"playbig"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
        self.avPlayer.isPlayer = NO;
        [[NSNotificationCenter defaultCenter] postNotificationName:@"pause" object:nil];
    } else {
        [self.avPlayer play];
        [self.startButton setImage:[[UIImage imageNamed:@"pausebig"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]forState:UIControlStateNormal];
        self.avPlayer.isPlayer = YES;
        [[NSNotificationCenter defaultCenter] postNotificationName:@"pause" object:nil];
    }
    [self timeRemove];
}


/*********************************************************/
#pragma mark - 下载
- (void)downLoad {
    [self timeRemove];
    
    
    
}




#pragma mark - 锁屏
- (void)lock {
    [self timeRemove];
    self.avPlayer.isLock = YES;
    if (self.avPlayer.isLock == YES) {
        self.lockingButton.hidden = NO;
        [self.timer invalidate];
        self.timer = nil;
        self.descView.hidden = YES;
        self.topView.hidden = YES;
        self.volumeSlider.hidden = YES;
        [self.lockingButton setImage:[[UIImage imageNamed:@"lock2"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
        [self timeLockHidden];
    }
}
- (void)locking {
    
    self.avPlayer.isLock = NO;
    [self.lockingButton setImage:[[UIImage imageNamed:@"lock1"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    
    self.timerLocking = [NSTimer scheduledTimerWithTimeInterval:3.0f target:self selector:@selector(lockishidden) userInfo:nil repeats:NO];
}


/*********************************************************/
#pragma mark - 播放的清晰度
- (void)autoDefinition {
    [self timeRemove];
        if (self.avPlayer.changeType == 2) {
            self.avPlayer.changeType = 0;
        } else {
            self.avPlayer.changeType += 1;
        }
//    CMTime presentTime = self.avPlayer.currentItem.currentTime;
//    CGFloat presentFloatTim = (CGFloat)presentTime.value/presentTime.timescale;
#warning bug----
    /////
//    CMTime presentTime = self.avPlayer.currentItem.currentTime;
//    
//    
//    CMTime totalTime = self.avPlayer.currentItem.duration;
//    
//    CGFloat presentFloatTim = (CGFloat)presentTime.value/presentTime.timescale;
//    
//    
//    CGFloat totalFloatTim = (CGFloat)totalTime.value / totalTime.timescale;
    
//    self.playSlider.value = presentFloatTim / totalFloatTim;
//        if (self.avPlayer.currentItem.duration.value) {
//            [self.avPlayer seekToTime:CMTimeMakeWithSeconds(self.avPlayer.currentItem.duration.value / self.avPlayer.currentItem.duration.timescale * self.playSlider.value, self.avPlayer.currentTime.timescale) completionHandler:^(BOOL finished) {
//                [self.avPlayer play];
//            }];
//        }
//    if (self.avPlayer.currentItem.duration.value) {
//        [self.avPlayer seekToTime:CMTimeMakeWithSeconds(presentFloatTim, self.avPlayer.currentTime.timescale) completionHandler:^(BOOL finished) {
//            [self.avPlayer play];
//        }];
//    }
    
    
    
        //给播放模式附图片
        if (self.avPlayer.changeType == 0) {   // 标清
            [self.autoButton setImage:[[UIImage imageNamed:@"puqing"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
            //
            [self creatMVPlay];
        }
       else if (self.avPlayer.changeType == 1) {   // 高清
            [self.autoButton setImage:[[UIImage imageNamed:@"gaoqing"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
            [self creatMVPlay];
        }
       else if (self.avPlayer.changeType == 2) {   // 超清
            [self.autoButton setImage:[[UIImage imageNamed:@"chaoqing"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
            [self creatMVPlay];
        }
    
    
}




/*********************************************************/
#pragma mark - 播放模式     type＝1
// 顺序 round      单曲 onlyOne    随机 random
- (void)typeChange {
    if (self.avPlayer.changeItem == 2) {
        self.avPlayer.changeItem = 0;
    } else {
        self.avPlayer.changeItem += 1;
    }
    //给播放模式附图片
    if (self.avPlayer.changeItem == 1) {   // 循环播放
        self.avPlayer.isRadom = NO;
        [self.changeButton setImage:[[UIImage imageNamed:@"danqu"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]  forState:UIControlStateNormal];
    }
    if (self.avPlayer.changeItem == 2) {   // 随机播放
        self.avPlayer.isRadom = YES;
        [self.changeButton setImage:[[UIImage imageNamed:@"suiji"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]  forState:UIControlStateNormal];
    }
    if (self.avPlayer.changeItem == 0) {   // 顺序播放
        self.avPlayer.isRadom = NO;
        [self.changeButton setImage:[[UIImage imageNamed:@"shunxu"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]  forState:UIControlStateNormal];
    }

    
    /////
    [self timeRemove];
}

#pragma mark - 播放模式
- (void)judgeType {
    
//    if (self.playSlider.value == 1) {
        if (self.avPlayer.changeItem == 0) {
            [self typeWithRound];
        }
        else if (self.avPlayer.changeItem == 1) {
            [self typeWithOnlyOne];
        }
        else if (self.avPlayer.changeItem == 2) {
            [self typeWithRandom];
        }
        

//    }
    
}


#pragma mark - 顺序
- (void)typeWithRound {
    if (self.avPlayer.MVList.count == 1) {
        
        [self creatMVPlay];
        
    } else {
        [self backMV];
    }
}
#pragma mark - 单曲
- (void)typeWithOnlyOne {
    
    [self creatMVPlay];
}
#pragma mark - 随机
- (void)typeWithRandom {
    if (self.avPlayer.MVList.count == 1) {
        
        [self creatMVPlay];
    } else {
        [self backMV];
    }
}
#pragma mark - 上一曲
- (void)frontMV {
    [self timeRemove];
    if (self.avPlayer.isRadom == YES) {
        self.avPlayer.indexPathNum = arc4random()%(self.avPlayer.MVList.count - 1);
        
    } else {
        if (self.avPlayer.indexPathNum == 0) {
            self.avPlayer.indexPathNum = self.avPlayer.MVList.count - 1;
        } else {
            self.avPlayer.indexPathNum -= 1;
        }
    }
    if (self.avPlayer.isPlayer == NO) {
        [self.startButton setImage:[UIImage imageNamed:@"pausebig"] forState:UIControlStateNormal];
        self.avPlayer.isPlayer = YES;
    }
    
    [self creatMVPlay];
    
}


#pragma mark - 下一曲
- (void)backMV {
    [self timeRemove];
    
    if (self.avPlayer.pageType == 2) {
        [self searchFromList];
    }
    
    if (self.isCollect == NO) {
        [self.collectButton setImage:[[UIImage imageNamed:@"collect1"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    } else {
        [self.collectButton setImage:[[UIImage imageNamed:@"collect2"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    }
    
    if (self.avPlayer.isRadom == YES) {
        self.avPlayer.indexPathNum = arc4random()%(self.avPlayer.MVList.count - 1);
        
    } else {
        if (self.avPlayer.indexPathNum == (self.avPlayer.MVList.count - 1)) {
            self.avPlayer.indexPathNum = 0;
        } else {
            self.avPlayer.indexPathNum += 1;
        }
    }
    if (self.avPlayer.isPlayer == NO) {
        [self.startButton setImage:[UIImage imageNamed:@"pausebig"] forState:UIControlStateNormal];
        self.avPlayer.isPlayer = YES;
    }
    
    [self creatMVPlay];
}



#pragma mark - 大屏标题
- (void)getTitleText {
    switch (self.avPlayer.pageType) {
        case 1:
        {
            if (self.avPlayer.MVList.count != 0) {
                self.homeModel = self.avPlayer.MVList[self.avPlayer.indexPathNum];
                self.titleLabel.text = self.homeModel.title;
            }
        }  break;
        case 2:
        {
            if (self.avPlayer.MVList.count != 0) {
                self.channelModel = self.avPlayer.MVList[self.avPlayer.indexPathNum];
                self.titleLabel.text = self.channelModel.title;
            }
        }   break;
        default:
            break;
    }
}



#pragma mark - 播放mv
- (void)creatMVPlay {
    
    Reachability *wiFi = [Reachability reachabilityForLocalWiFi];
    Reachability *_3G = [Reachability reachabilityForInternetConnection];
    if ([wiFi isReachableViaWiFi] == 1 || [_3G isReachable] == 1) {
        [MBProgressHUD showHUDAddedTo:self.playView animated:YES];
        if (self.avPlayer.MVList.count != 0) {
            
            [self.imView removeFromSuperview];
            
            
            
            if (self.avPlayer.pageType == 1) {
                self.homeModel = self.avPlayer.MVList[self.avPlayer.indexPathNum];
                
                switch (self.avPlayer.changeType) {
                    case 0:
                    {
                        if (self.homeModel.url) {
                            [self.avPlayer playWithUrl:self.homeModel.url];
                        }
                        //                    else if (self.homeModel.uhdUrl) {
                        //                        [self.avPlayer playWithUrl:self.homeModel.uhdUrl];
                        //                    }
                        NSLog(@"当前播放的是普清");
                    }
                        break;
                    case 1:
                    {
                        if (self.homeModel.hdUrl) {
                            [self.avPlayer playWithUrl:self.homeModel.hdUrl];
                        } else if (self.homeModel.url) {
                            [self.avPlayer playWithUrl:self.homeModel.url];
                        }
                        //                    else if (self.homeModel.uhdUrl) {
                        //                        [self.avPlayer playWithUrl:self.homeModel.uhdUrl];
                        //                    }
                        NSLog(@"当前播放的是高清");
                    }
                        break;
                    case 2:
                    {
                        if (self.homeModel.shdUrl) {
                            [self.avPlayer playWithUrl:self.homeModel.shdUrl];
                        } else if (self.homeModel.hdUrl) {
                            [self.avPlayer playWithUrl:self.homeModel.hdUrl];
                        } else if (self.homeModel.url) {
                            [self.avPlayer playWithUrl:self.homeModel.url];
                        }
                        //                    else if (self.homeModel.uhdUrl) {
                        //                        [self.avPlayer playWithUrl:self.homeModel.uhdUrl];
                        //                    }
                        NSLog(@"当前播放的是超清");
                    }
                        break;
                    default:
                        break;
                }
                
                
                
                [self getTitleText];
                [self.avPlayer play];
                self.avPlayer.isPlayer = YES;
            }
            
            else if (self.avPlayer.pageType == 2) {
                self.channelModel = self.avPlayer.MVList[self.avPlayer.indexPathNum];
                
                switch (self.avPlayer.changeType) {
                    case 0:
                    {
                        if (self.channelModel.url) {
                            [self.avPlayer playWithUrl:self.channelModel.url];
                        }
                        //                    else if (self.channelModel.uhdUrl) {
                        //                        [self.avPlayer playWithUrl:self.channelModel.uhdUrl];
                        //                    }
                        NSLog(@"当前播放的是普清");
                    }
                        break;
                    case 1:
                    {
                        if (self.channelModel.hdUrl) {
                            [self.avPlayer playWithUrl:self.channelModel.hdUrl];
                        } else if (self.channelModel.url) {
                            [self.avPlayer playWithUrl:self.channelModel.url];
                        }
                        //                    else if (self.channelModel.uhdUrl) {
                        //                        [self.avPlayer playWithUrl:self.channelModel.uhdUrl];
                        //                    }
                        NSLog(@"当前播放的是高清");
                    }
                        break;
                    case 2:
                    {
                        if (self.channelModel.shdUrl) {
                            [self.avPlayer playWithUrl:self.channelModel.shdUrl];
                        } else if (self.channelModel.hdUrl) {
                            [self.avPlayer playWithUrl:self.channelModel.hdUrl];
                        } else if (self.channelModel.url) {
                            [self.avPlayer playWithUrl:self.channelModel.url];
                        }
                        //                    else if (self.channelModel.uhdUrl) {
                        //                        [self.avPlayer playWithUrl:self.channelModel.uhdUrl];
                        //                    }
                        NSLog(@"当前播放的是超清");
                    }
                        break;
                    default:
                        break;
                }
                
                
                [self getTitleText];
                [self.avPlayer play];
                self.avPlayer.isPlayer = YES;
            }
            [MBProgressHUD hideHUDForView:self.playView animated:YES];
            //通知当前播放的为第几个
            [[NSNotificationCenter defaultCenter] postNotificationName:@"gg" object:[NSNumber numberWithInteger:self.avPlayer.indexPathNum]];
            
            
        } else {
            [self.playView removeFromSuperview];
            self.imView = [[UIImageView alloc] initWithFrame:self.view.bounds];
            [self.view addSubview:self.imView];
            self.imView.image = [UIImage imageNamed:@"wu"];
            [MBProgressHUD hideHUDForView:self.playView animated:YES];
        }
        
    } else {
        [MBProgressHUD showAlertView:@"" andMessage:@"网络错误"];
    }
}







#pragma mark - 收藏
- (void)collect {
    [self timeRemove];

    if (self.isCollect == NO) {
        if (self.avPlayer.pageType == 1) {
            YSingleCollection *ySingleCollection = [NSEntityDescription insertNewObjectForEntityForName:@"YSingleCollection" inManagedObjectContext:self.coreDataManager.managedObjectContext];
            
            ySingleCollection.creatImage = self.ymvModel.creatorModel.largeAvatar;
            ySingleCollection.detailId = [NSString stringWithFormat:@"%@", self.ymvModel._id];
//            NSLog(@"----%ld", self.ymvModel._id.integerValue);
//            NSLog(@" ^^^^ %ld", ySingleCollection.detailId.integerValue);
            ySingleCollection.intergral = [NSNumber numberWithInteger:self.ymvModel.integral.integerValue];
            ySingleCollection.listImage = self.ymvModel.playListBigPic;
            ySingleCollection.nickName = self.ymvModel.creatorModel.nickName;
            ySingleCollection.title = self.ymvModel.title;
            ySingleCollection.totalViews = [NSString stringWithFormat:@"%@", self.ymvModel.totalViews];
            ySingleCollection.videoCount = self.ymvModel.videoCount;
            
            [self.coreDataManager saveContext];
            
            
        } else {
            MVCollection *mvCollection = [NSEntityDescription insertNewObjectForEntityForName:@"MVCollection" inManagedObjectContext:self.coreDataManager.managedObjectContext];
            mvCollection.artistName = self.channelModel.artistName;
            mvCollection.hdUrl = self.channelModel.hdUrl;
            mvCollection.idName = [NSString stringWithFormat:@"%@", self.channelModel.idName];
            mvCollection.posterPic = self.channelModel.posterPic;
            mvCollection.title = self.channelModel.title;
            mvCollection.totalViews = self.channelModel.totalViews;
            mvCollection.albumImage = self.channelModel.albumImg;
            
            [self.coreDataManager saveContext];
            
        }
        self.isCollect = YES;
        [self.collectButton setImage:[[UIImage imageNamed:@"collect2"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
        

    } else {
        if (self.avPlayer.pageType == 1) {
            for (YSingleCollection *collect in self.mvCollectArr) {
                if ([collect.detailId isEqualToString:[NSString stringWithFormat:@"%@", self.ymvModel._id]]) {
                    [self.coreDataManager.managedObjectContext deleteObject:collect];
                    [self.coreDataManager saveContext];
                    self.isCollect = NO;
                    [self.collectButton setImage:[[UIImage imageNamed:@"collect1"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
                    
                }
            }
        } else {
            for (MVCollection *collect in self.mvCollectArr) {
                if (collect.idName == [NSNumber numberWithInteger:self.channelModel.idName.integerValue]) {
                    [self.coreDataManager.managedObjectContext deleteObject:collect];
                    [self.coreDataManager saveContext];
                    self.isCollect = NO;
                    [self.collectButton setImage:[[UIImage imageNamed:@"collect1"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
                    
                }
            }
        }
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:@"CollectReload" object:nil userInfo:nil];
    
}











#pragma mark - slider事件
- (void)sliderAction {
    //    CMTimeMakeWithSeconds
    //    参数1:跳转到的时间
    //    参数2:每秒多少帧 （fps）
    //位加载拉slider  bug
    if (self.avPlayer.currentItem.duration.value) {
        [self.avPlayer seekToTime:CMTimeMakeWithSeconds(self.avPlayer.currentItem.duration.value / self.avPlayer.currentItem.duration.timescale * self.playSlider.value, self.avPlayer.currentTime.timescale) completionHandler:^(BOOL finished) {
            [self.startButton setImage:[[UIImage imageNamed:@"pausebig"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
            self.avPlayer.isPlayer = YES;
            [self.avPlayer play];
        }];
    }
}
#pragma mark - slider timer action
- (void)timeAction {
    
    CMTime presentTime = self.avPlayer.currentItem.currentTime;
    
    
    CMTime totalTime = self.avPlayer.currentItem.duration;
    
    CGFloat presentFloatTim = (CGFloat)presentTime.value/presentTime.timescale;
    
    
    CGFloat totalFloatTim = (CGFloat)totalTime.value / totalTime.timescale;
    
    self.playSlider.value = presentFloatTim / totalFloatTim;
    
    NSDate *presentDate = [NSDate dateWithTimeIntervalSince1970:presentFloatTim];
    NSDate *totalDate = [NSDate dateWithTimeIntervalSince1970:totalFloatTim];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    if (totalFloatTim / 3600 >= 1) {
        [formatter setDateFormat:@"HH:mm:ss"];
    }else {
        [formatter setDateFormat:@"m:ss"];
    }
    
    NSString *presentStrTime = [formatter stringFromDate:presentDate];
    NSString *totalStrTime = [formatter stringFromDate:totalDate];
    
    
    
    NSString *string1 = [NSString stringWithFormat:@"%@", presentStrTime];
    NSString *string2 = [NSString stringWithFormat:@"%@", totalStrTime];
    
    self.timeBeginLabel.text = string1;
    self.timeEndLabel.text = string2;
   
    
}
- (void)getData {
    if (self.avPlayer.pageType == 1) {
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"YSingleCollection" inManagedObjectContext:self.coreDataManager.managedObjectContext];
        [fetchRequest setEntity:entity];
        // Specify criteria for filtering which objects to fetch
        
        NSError *error = nil;
        NSArray *fetchedObjects = [self.coreDataManager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
        if (fetchedObjects == nil) {
            
        } else {
            for (YSingleCollection *ySingleCollect in fetchedObjects) {
                [self.mvCollectArr addObject:ySingleCollect];
            }
            
        }
    } else {
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"MVCollection" inManagedObjectContext:self.coreDataManager.managedObjectContext];
        [fetchRequest setEntity:entity];
        // Specify criteria for filtering which objects to fetch
        
        
        NSError *error = nil;
        NSArray *fetchedObjects = [self.coreDataManager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
        if (fetchedObjects == nil) {
            
        } else {
            for (MVCollection *mvCollect in fetchedObjects) {
                [self.mvCollectArr addObject:mvCollect];
            }
        }
    }

}

#pragma mark - searchFromList
- (void)searchFromList {
    if (self.avPlayer.pageType == 1) {
        
            for (YSingleCollection *ySingleCollect in self.mvCollectArr) {
                if ([ySingleCollect.detailId isEqualToString:[NSString stringWithFormat:@"%@", self.ymvModel._id]]) {
                    self.isCollect = YES;
                }
            }
            
        } else {
        
            for (MVCollection *mvCollect in self.mvCollectArr) {
                if (mvCollect.idName == self.channelModel.idName) {
                    self.isCollect = YES;
                }
            }
        }

}

//隐藏顶部状态栏
- (BOOL)prefersStatusBarHidden {
    return YES;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
@end


